

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 1. Axios 简介 Axios GitHub 地址：https:&#x2F;&#x2F;github.com&#x2F;axios&#x2F;axiosAxios 官网：https:&#x2F;&#x2F;axios-http.com&#x2F;Axios 是用于浏览器和 node.js 的基于 Promise 的 HTTP 客户端  Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境，运用非常广泛，前端框架例如">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析">
<meta property="og:url" content="http://example.com/2022/08/19/Vue2%20%E5%BC%80%E5%8F%91%E6%80%BB%E7%BB%93%20axios%20%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85%20_%20%E8%AF%B7%E6%B1%82%E3%80%81%E5%93%8D%E5%BA%94%E3%80%81%E6%B8%B2%E6%9F%93%E7%9A%84%E5%A4%A7%E8%87%B4%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 1. Axios 简介 Axios GitHub 地址：https:&#x2F;&#x2F;github.com&#x2F;axios&#x2F;axiosAxios 官网：https:&#x2F;&#x2F;axios-http.com&#x2F;Axios 是用于浏览器和 node.js 的基于 Promise 的 HTTP 客户端  Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境，运用非常广泛，前端框架例如">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/6715e875cedd4fc7bba9301b14b3c9e1.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/544e8e358b687d644daefdd6c24ee1fe.jpeg">
<meta property="article:published_time" content="2022-08-19T07:03:36.000Z">
<meta property="article:modified_time" content="2022-08-22T15:49:36.471Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="开发总结">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/6715e875cedd4fc7bba9301b14b3c9e1.png">
  
  
  
  <title>Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-08-19 15:03" pubdate>
          2022年8月19日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.4k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          37 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="1-Axios-简介"><a href="#1-Axios-简介" class="headerlink" title="1. Axios 简介"></a>1. Axios 简介</h1><hr>
<p>Axios GitHub 地址：<a target="_blank" rel="noopener" href="https://github.com/axios/axios">https://github.com/axios/axios</a><br>Axios 官网：<a target="_blank" rel="noopener" href="https://axios-http.com/">https://axios-http.com/</a><br>Axios 是用于浏览器和 node.js 的基于 Promise 的 HTTP 客户端</p>
<blockquote>
<p>Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境，运用非常广泛，前端框架例如 React、Vue 都是基于 Node.js 开发的，Node.js 可以开发 Web 应用程序中的后台系统。<br>（我们平时使用的 npm 命令本质上就是通过 Node.js 来运行的）</p>
</blockquote>
<blockquote>
<p>Promise 是由 JavaScript 中实现的 ECMAScript6 规范推出的新特性，主要解决了 JS 回调地狱的问题，通常用于异步编程，可以更好的处理回调的场景</p>
</blockquote>
<p>Axios 本质上是 AJAX 的拓展版，所以它的功能和 AJAX 一样，向指定的 URL 发送请求，并处理结果。在 Github <a target="_blank" rel="noopener" href="https://github.com/axios/axios">https://github.com/axios/axios</a> 上，官方给出了许多示例。</p>
<h1 id="2-Vue2二次封装Axios"><a href="#2-Vue2二次封装Axios" class="headerlink" title="2. Vue2二次封装Axios"></a>2. Vue2二次封装Axios</h1><hr>
<p>由于我目前仅接触过Vue2，所以本篇的 Axios 是基于 Vue2版本对其应用。<br><strong>运行环境：</strong></p>
<ul>
<li>“axios”: “^0.17.1”</li>
<li>“vue”: “^2.5.2”</li>
<li>“element-ui”: “^2.0.10”</li>
</ul>
<h2 id="2-1-定义简易的-Token-工具脚本文件"><a href="#2-1-定义简易的-Token-工具脚本文件" class="headerlink" title="2.1 定义简易的 Token 工具脚本文件"></a>2.1 定义简易的 Token 工具脚本文件</h2><p>在之前的学习中，我们会把用户登录信息记录到 session，但是这种方式的安全性并不高，只要拿到 浏览器的 sessionId 就可以在异地登录。而使用 token 能更好的记录用户信息，因为 token 相当于用户的身份凭证，具有时效性，既可以设置过期时间，又可以用来检验身份，同时支持在多个设备登录，为了方便，我们通过 浏览器支持的 JavaScript 内置对象 localStorage 来管理 token。<br><code>token.js</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getToken</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">localStorage</span>.<span class="hljs-property">token</span><br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">setToken</span>(<span class="hljs-params">token</span>) &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">localStorage</span>.<span class="hljs-property">token</span> = token<br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">removeToken</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">localStorage</span>.<span class="hljs-title function_">removeItem</span>(<span class="hljs-string">&#x27;token&#x27;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="2-2-封装-Axios"><a href="#2-2-封装-Axios" class="headerlink" title="2.2 封装 Axios"></a>2.2 封装 Axios</h2><p><code>index.js</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123;getToken&#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/request/token&#x27;</span><br><br><span class="hljs-keyword">const</span> service = axios.<span class="hljs-title function_">create</span>(&#123;<br>  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">&#x27;http://localhost:8888&#x27;</span>,	<span class="hljs-comment">// 设置请求的地址</span><br>  <span class="hljs-attr">timeout</span>: <span class="hljs-number">10000</span>										<span class="hljs-comment">// 设置超时时间, 10000 ms </span><br>&#125;)<br><span class="hljs-comment">//request拦截器: 用于封装请求头</span><br>service.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-function"><span class="hljs-params">req</span> =&gt;</span> &#123;<br>  <br>  <span class="hljs-keyword">if</span> (store.<span class="hljs-property">state</span>.<span class="hljs-property">token</span>) &#123;<br>    req.<span class="hljs-property">headers</span>[<span class="hljs-string">&#x27;Oauth-Token&#x27;</span>] = <span class="hljs-title function_">getToken</span>() || <span class="hljs-string">&#x27;&#x27;</span>		<span class="hljs-comment">// 设置请求头</span><br>  &#125;<br>  <span class="hljs-keyword">return</span> config<br>&#125;, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> &#123;<br><br>  <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error)															<span class="hljs-comment">// 返回异常信息</span><br>&#125;)<br><br><span class="hljs-comment">// respone拦截器: 用于封装响应体</span><br>service.<span class="hljs-property">interceptors</span>.<span class="hljs-property">response</span>.<span class="hljs-title function_">use</span>(<br>  <span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> &#123;<br><br>    <span class="hljs-keyword">const</span> res = response.<span class="hljs-property">data</span>;<br><br>    <span class="hljs-comment">//0 为成功状态</span><br>    <span class="hljs-keyword">if</span> (res.<span class="hljs-property">code</span> !== <span class="hljs-number">200</span>) &#123;<br>      <br>      <span class="hljs-comment">//90001 Session超时</span><br>      <span class="hljs-keyword">if</span> (res.<span class="hljs-property">code</span> === <span class="hljs-number">90001</span>) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;error&#x27;</span>);<br>      &#125;<br><br>      <span class="hljs-comment">//20001 用户未登录</span><br>      <span class="hljs-keyword">if</span> (res.<span class="hljs-property">code</span> === <span class="hljs-number">90002</span>) &#123;<br><br>        <span class="hljs-variable language_">this</span>.$message(&#123;<br>          <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;warning&#x27;</span>,<br>          <span class="hljs-attr">showClose</span>: <span class="hljs-literal">true</span>,<br>          <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;未登录或登录超时，请重新登录哦&#x27;</span><br>        &#125;)<br><br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;error&#x27;</span>);<br>      &#125;<br><br>      <span class="hljs-comment">//70001 权限认证错误</span><br>      <span class="hljs-keyword">if</span> (res.<span class="hljs-property">code</span> === <span class="hljs-number">70001</span>) &#123;<br>        <span class="hljs-variable language_">this</span>.$message(&#123;<br>          <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;warning&#x27;</span>,<br>          <span class="hljs-attr">showClose</span>: <span class="hljs-literal">true</span>,<br>          <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;你没有权限访问哦&#x27;</span><br>        &#125;)<br>        <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;error&#x27;</span>);<br>      &#125;<br><br>      <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(res.<span class="hljs-property">msg</span>);<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>      <span class="hljs-keyword">return</span> response.<span class="hljs-property">data</span>;<br>    &#125;<br>  &#125;,<br>  <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> &#123;<br>    <span class="hljs-variable language_">this</span>.$message(&#123;<br>      <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;warning&#x27;</span>,<br>      <span class="hljs-attr">showClose</span>: <span class="hljs-literal">true</span>,<br>      <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;连接超时&#x27;</span><br>    &#125;)<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-string">&#x27;error&#x27;</span>)<br>  &#125;)<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> service<br></code></pre></td></tr></table></figure>

<p>ES6 支持模块化编程，Node.js 支持 ES6 规范，而 Vue2 是基于 Node.js 的，所以可以使用模块化的思想来设计，目前，设计的封装脚本以及 Token 脚本可以视为工具脚本。</p>
<h2 id="2-3-使用-Axios-二次封装的脚本"><a href="#2-3-使用-Axios-二次封装的脚本" class="headerlink" title="2.3 使用 Axios 二次封装的脚本"></a>2.3 使用 Axios 二次封装的脚本</h2><p>除了对 Axios 封装外，我们需要知道如何使用这个工具，在之前的基础上，我们封装了 Axios，接下来基于它，给出一个注册、登录、退出请求的 Demo：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/request&#x27;</span><br><br><span class="hljs-comment">// 登录</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">login</span>(<span class="hljs-params">account, password</span>) &#123;<br>  <span class="hljs-keyword">const</span> data = &#123;<br>    account,<br>    password<br>  &#125;<br>  <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/login&#x27;</span>,<br>    <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;post&#x27;</span>,<br>    data<br>  &#125;)<br>&#125;<br><br><span class="hljs-comment">// 注销</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">logout</span>(<span class="hljs-params">token</span>) &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">headers</span>: &#123;<span class="hljs-string">&#x27;Authorization&#x27;</span>: token&#125;,<br>    <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/logout&#x27;</span>,<br>    <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;get&#x27;</span><br>  &#125;)<br>&#125;<br><span class="hljs-comment">// 获取用户信息</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getUserInfo</span>(<span class="hljs-params">token</span>) &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">headers</span>: &#123;<span class="hljs-string">&#x27;Authorization&#x27;</span>: token&#125;,<br>    <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/users/currentUser&#x27;</span>,<br>    <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;get&#x27;</span><br>  &#125;)<br>&#125;<br><span class="hljs-comment">// 注册</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">register</span>(<span class="hljs-params">account, nickname, password</span>) &#123;<br>  <span class="hljs-keyword">const</span> data = &#123;<br>    account,<br>    nickname,<br>    password<br>  &#125;<br>  <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/register&#x27;</span>,<br>    <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;post&#x27;</span>,<br>    data<br>  &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>
<p>上述代码是支持用户注册、登录、获取用户信息、退出登录接口访问的一个工具脚本，这种脚本通常是放在 api 文件夹下的。<br>虽然代码看起来不复杂，但是其实它用到了一些 ES6 的特性。</p>
<ol>
<li>import 可以导入其他 .js 中 export 导出的模块</li>
<li>export function 可以导出函数，供其他的 js 脚本引用</li>
<li>const 变量名 &#x3D; {变量1, 变量2, 变量3} 是 对象赋值的简写形式，例如:  { a } 本质上是指{ “a” : a } </li>
<li>封装的 request 返回的值是一个 Promise 对象，可以调用 then方法来触发响应的结果。</li>
<li>封装 request 调用了 this.$message方法，本质上调用了 Vue 组件绑定的 element-ui 提供的方法，从ES6 开始之后的版本， 函数里的 this 就是调用该函数的对象，若没有则默认为 window，这里调用 request 对象的本质上是 Vuex 中的 action 层，由于 Vuex 是作为插件被注册到 Vue的，所以 request 里的函数指向的 this ，就是调用 action 层时的那个 Vue 组件。</li>
</ol>
<h2 id="2-4-在-Vuex-中的-action-层使用-api"><a href="#2-4-在-Vuex-中的-action-层使用-api" class="headerlink" title="2.4 在 Vuex 中的 action 层使用 api"></a>2.4 在 Vuex 中的 action 层使用 api</h2><p><a target="_blank" rel="noopener" href="https://vuex.vuejs.org/zh/">Vuex</a> 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。</p>
<p>Vuex 主要分为三个部分：</p>
<ul>
<li>状态 state，驱动引用的数据源</li>
<li>视图 view，以声明方式将状态state 映射到视图</li>
<li>操作 actions，响应在视图上的用户输入导致的状态变化</li>
</ul>
<p>官方提供的示例图：<br><img src="https://img-blog.csdnimg.cn/6715e875cedd4fc7bba9301b14b3c9e1.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p> store 的相关代码就不展示了，主要是介绍这种思想，只要给 Vue2 程序注册了 Vuex，那么我们可以在任何一个组件里调用 Vuex 的相关属性，state的变量，或者 actions 、mutations 层的方法，其中 action 层会调用 Axios 的方法获取数据，然后在将数据保存到 state 中。</p>
<p>那么数据是如何展示的呢？很简单，通过 Vue2 的计算属性即可，例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-attr">computed</span>: &#123;<br>  <span class="hljs-title function_">userInfo</span>(<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-property">state</span>.<span class="hljs-property">userInfo</span><br>  &#125;<br>&#125;,<br></code></pre></td></tr></table></figure>

<p>因为 Axios 请求的大部分都是异步的，所以我们不能在 axios 相关的回调函数里获取到数据，而是获取 Vuex 中 state 层存储的数据。</p>
<h1 id="3-总结"><a href="#3-总结" class="headerlink" title="3. 总结"></a>3. 总结</h1><hr>
<p>以登录请求为例，整个过程如下：<br><img src="https://img-blog.csdnimg.cn/img_convert/544e8e358b687d644daefdd6c24ee1fe.jpeg" srcset="/img/loading.gif" lazyload><br>大致的过程如上图所示，这里暂时没有考虑 vue-router 路由相关的问题。可以看出，由 Vue 实现的前端组件开发，整个流程还是比较清晰的，分别有哪些部分，每个部分各自是做什么工作的，这几个问题理清楚了就行。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%89%8D%E7%AB%AF/" class="category-chain-item">前端</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Vue/">#Vue</a>
      
        <a href="/tags/%E5%BC%80%E5%8F%91%E6%80%BB%E7%BB%93/">#开发总结</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析</div>
      <div>http://example.com/2022/08/19/Vue2 开发总结 axios 二次封装 _ 请求、响应、渲染的大致流程分析/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年8月19日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/08/21/C%E8%AF%AD%E8%A8%80%20%E5%AE%9E%E7%8E%B0%E8%B4%AA%E5%90%83%E8%9B%87%20_%20%E5%8D%81%E5%88%86%E9%92%9F%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B%20_%20%E5%88%9D%E5%AD%A6%E8%80%85%E6%A1%88%E4%BE%8B%20_%20%E9%99%84%E5%B8%A6%E8%AE%BE%E8%AE%A1%E6%80%9D%E8%B7%AF%20+%20%E4%BB%A3%E7%A0%81%20+%20%E5%9B%BE%E6%96%87%E5%88%86%E6%9E%90/" title="C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">C语言 实现贪吃蛇 _ 十分钟入门案例 _ 初学者案例 _ 附带设计思路 + 代码 + 图文分析</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/08/16/JavaScript%20%E7%AC%94%E8%AE%B01%20ES6%20%E6%96%B0%E7%89%B9%E6%80%A7%20_%20%E8%A7%A3%E6%9E%84%E8%B5%8B%E5%80%BC%E3%80%81%E6%A8%A1%E6%9D%BF%E5%AD%97%E7%AC%A6%E4%B8%B2%E3%80%81Symbol%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E3%80%81Promise%E3%80%81%E6%A8%A1%E5%9D%97%E5%8C%96/" title="JavaScript 笔记1 ES6 新特性 _ 解构赋值、模板字符串、Symbol数据类型、Promise、模块化">
                        <span class="hidden-mobile">JavaScript 笔记1 ES6 新特性 _ 解构赋值、模板字符串、Symbol数据类型、Promise、模块化</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
